package com.stanwind.wmqtt.auth.aliyun;

import com.stanwind.wmqtt.auth.AuthSettingFactory;
import com.stanwind.wmqtt.auth.domain.MQTTBasicAuthInfo;
import com.stanwind.wmqtt.auth.domain.MQTTClientConnData;
import com.stanwind.wmqtt.auth.domain.MQTTServerConnData;
import com.stanwind.wmqtt.utils.Tools;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

import static org.eclipse.paho.client.mqttv3.MqttConnectOptions.MQTT_VERSION_3_1_1;

/**
 * AliSignSettingFactory 阿里云签名模式MQTT
 *
 * @author : Stan
 * @version : 1.0
 * @date :  2020-11-11 15:58
 **/
public class AliSignSettingFactory implements AuthSettingFactory {

    @Autowired
    private AliApi aliApi;

    /**
     * 获取登录数据
     *
     * @param readTopics
     * @param writeTopics
     */
    @Override
    public MQTTClientConnData getClientConnData(List<String> readTopics, List<String> writeTopics) throws Exception {
        return aliApi.getClientConnData(TOKEN_EXPIRE, readTopics, writeTopics);
    }

    /**
     *
     * @param serverURIs
     * @param keepAliveInterval
     * @param authBean
     * @return
     * @throws Exception
     */
    @Override
    public MQTTServerConnData getServerConnData(String[] serverURIs, Integer keepAliveInterval, MQTTBasicAuthInfo authBean)
            throws Exception {
        MqttConnectOptions options = new MqttConnectOptions();
        options.setServerURIs(serverURIs);
        options.setUserName("Signature|" + authBean.getAccessKey() + "|" + authBean.getInstanceId());
        options.setPassword(Tools.macSignature(authBean.getClientId(), authBean.getSecretKey()).toCharArray());
        options.setCleanSession(false);
        options.setKeepAliveInterval(keepAliveInterval);
        options.setAutomaticReconnect(true);
        options.setMqttVersion(MQTT_VERSION_3_1_1);
        options.setConnectionTimeout(5000);

        return new MQTTServerConnData().setConnectOptions(options);
    }
}
